package sdk.org.apache.shiro.G2_使用.C08_会话管理_1会话管理器;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.subject.Subject;

import com.titan.core.utils.data.CollectionUtils;
import com.titan.core.utils.data.FormatUtils;
import com.titan.core.utils.data.ListUtils;
import com.titan.core.utils.debug.Timer;
import com.titan.core.utils.io.ConsoleUtils;
import com.titan.core.utils.thread.ThreadUtils;

import sdk.org.apache.shiro.utils.ShiroUtils;

public class 会话管理器_DefaultSessionManager {
    public static void main(String[] args) {
        Timer timer = Timer.$();
        try {
            run(timer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            timer.print("执行总用时");
            System.exit(0);
        }
    }
    private static void run(Timer timer) throws Exception {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        DefaultSessionManager sessionManager = new DefaultSessionManager();
        sessionManager.setGlobalSessionTimeout(1000);  // session的失效时长，单位:毫秒
        sessionManager.setDeleteInvalidSessions(true);  // 删除失效的session
        sessionManager.setSessionValidationSchedulerEnabled(true);  // 是否开启会话验证器，默认是开启的
        sessionManager.setSessionListeners(ListUtils.toList(new MySessionListener1(), new MySessionListener2()));
        securityManager.setSessionManager(sessionManager);
        
        SimpleAccountRealm realm = new SimpleAccountRealm();
        realm.addAccount("admin", "123");
        securityManager.setRealm(realm);
        
        SecurityUtils.setSecurityManager(securityManager);
        
        // 登录
        Subject currentUser = ShiroUtils.login("admin", "123", true);
        
        ConsoleUtils.log("用户 ["+currentUser.getPrincipal()+"] 的登录状态："+currentUser.isAuthenticated());
        
        // 会话信息
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        ConsoleUtils.log("会话中key[someKey]对应值", FormatUtils.toString(session.getAttribute("someKey")));
        ThreadUtils.sleep(1100);
        try {
            ConsoleUtils.log("会话中key[someKey]对应值", FormatUtils.toString(session.getAttribute("someKey")));
        } catch (org.apache.shiro.session.ExpiredSessionException e) {
            System.err.println(e.toString());
        }
        // 用户退出
        ShiroUtils.logout();
    }
}
